import React, { useState } from 'react';
import { Typography, Table, Card, Space, Button, Tag, Input, Select, Modal, Form, Row, Col } from 'antd';
import {
  GlobalOutlined,
  PlusOutlined,
  SettingOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;

interface Site {
  id: string;
  name: string;
  domain: string;
  status: 'running' | 'stopped' | 'building';
  ssl: boolean;
  visitors: number;
  lastUpdated: string;
  framework: string;
}

const SiteList: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [modalVisible, setModalVisible] = useState(false);
  const [editingSite, setEditingSite] = useState<Site | null>(null);
  const [form] = Form.useForm();

  // 模拟站点数据
  const [sites] = useState<Site[]>([
    {
      id: '1',
      name: '企业官网',
      domain: 'company.com',
      status: 'running',
      ssl: true,
      visitors: 1250,
      lastUpdated: '2024-01-15',
      framework: 'React'
    },
    {
      id: '2',
      name: '产品展示',
      domain: 'product.com',
      status: 'building',
      ssl: false,
      visitors: 0,
      lastUpdated: '2024-01-14',
      framework: 'Vue'
    },
    {
      id: '3',
      name: 'API文档',
      domain: 'api-docs.com',
      status: 'running',
      ssl: true,
      visitors: 560,
      lastUpdated: '2024-01-13',
      framework: 'Next.js'
    },
    {
      id: '4',
      name: '测试环境',
      domain: 'test.example.com',
      status: 'stopped',
      ssl: false,
      visitors: 25,
      lastUpdated: '2024-01-10',
      framework: 'Static'
    }
  ]);

  const getStatusConfig = (status: Site['status']) => {
    const configs = {
      running: { color: 'success', text: '运行中' },
      stopped: { color: 'default', text: '已停止' },
      building: { color: 'processing', text: '构建中' }
    };
    return configs[status];
  };

  const filteredSites = sites.filter(site => {
    const matchesSearch = site.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         site.domain.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter === 'all' || site.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const handleEdit = (site: Site) => {
    setEditingSite(site);
    form.setFieldsValue(site);
    setModalVisible(true);
  };

  const handleDelete = (site: Site) => {
    Modal.confirm({
      title: '确认删除站点',
      content: `确定要删除站点"${site.name}"吗？此操作不可逆转。`,
      icon: <ExclamationCircleOutlined />,
      okText: '确定删除',
      cancelText: '取消',
      okType: 'danger',
      onOk() {
        console.log('删除站点:', site.name);
        // 实现删除逻辑
      },
    });
  };

  const handleStatusChange = (site: Site, newStatus: Site['status']) => {
    console.log(`将站点 ${site.name} 状态改为 ${newStatus}`);
    // 实现状态更改逻辑
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      console.log('提交站点信息:', values);
      setModalVisible(false);
      setEditingSite(null);
      form.resetFields();
      // 实现保存逻辑
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const columns: ColumnsType<Site> = [
    {
      title: '站点信息',
      key: 'siteInfo',
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Space>
            <GlobalOutlined style={{ color: '#1890ff' }} />
            <Text strong>{record.name}</Text>
          </Space>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.domain}
          </Text>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: Site['status']) => {
        const config = getStatusConfig(status);
        return <Tag color={config.color}>{config.text}</Tag>;
      },
      filters: [
        { text: '运行中', value: 'running' },
        { text: '已停止', value: 'stopped' },
        { text: '构建中', value: 'building' },
      ],
    },
    {
      title: 'SSL',
      dataIndex: 'ssl',
      key: 'ssl',
      render: (ssl: boolean) => (
        <Tag color={ssl ? 'blue' : 'default'}>
          {ssl ? '已配置' : '未配置'}
        </Tag>
      ),
    },
    {
      title: '框架',
      dataIndex: 'framework',
      key: 'framework',
      render: (framework: string) => (
        <Tag>{framework}</Tag>
      ),
    },
    {
      title: '访问量',
      dataIndex: 'visitors',
      key: 'visitors',
      render: (visitors: number) => (
        <Text>{visitors.toLocaleString()}</Text>
      ),
      sorter: (a, b) => a.visitors - b.visitors,
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdated',
      key: 'lastUpdated',
      sorter: (a, b) => new Date(a.lastUpdated).getTime() - new Date(b.lastUpdated).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_, record) => (
        <Space size="small" wrap>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          
          <Button
            type="link"
            size="small"
            icon={<SettingOutlined />}
            onClick={() => console.log('配置站点:', record.name)}
          >
            配置
          </Button>
          
          {record.status === 'running' ? (
            <Button
              type="link"
              size="small"
              onClick={() => handleStatusChange(record, 'stopped')}
            >
              停止
            </Button>
          ) : (
            <Button
              type="link"
              size="small"
              onClick={() => handleStatusChange(record, 'running')}
            >
              启动
            </Button>
          )}
          
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 统计信息
  const stats = {
    total: sites.length,
    running: sites.filter(s => s.status === 'running').length,
    stopped: sites.filter(s => s.status === 'stopped').length,
    building: sites.filter(s => s.status === 'building').length,
    sslEnabled: sites.filter(s => s.ssl).length,
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'flex-start',
        marginBottom: '24px'
      }}>
        <div>
          <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
            <GlobalOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
            站点管理
          </Title>
          <Text type="secondary">管理您的网站和域名配置</Text>
        </div>
        <Button 
          type="primary" 
          size="large"
          icon={<PlusOutlined />}
          onClick={() => {
            setEditingSite(null);
            form.resetFields();
            setModalVisible(true);
          }}
        >
          新建站点
        </Button>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={6}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>{stats.total}</div>
              <div style={{ color: '#666' }}>总站点数</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>{stats.running}</div>
              <div style={{ color: '#666' }}>运行中</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#722ed1' }}>{stats.sslEnabled}</div>
              <div style={{ color: '#666' }}>SSL已配置</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#fa8c16' }}>{stats.building}</div>
              <div style={{ color: '#666' }}>构建中</div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space style={{ marginBottom: '16px' }}>
          <Input
            placeholder="搜索站点名称或域名"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
          <Select
            placeholder="选择状态"
            value={statusFilter}
            onChange={setStatusFilter}
            style={{ width: 150 }}
          >
            <Option value="all">全部状态</Option>
            <Option value="running">运行中</Option>
            <Option value="stopped">已停止</Option>
            <Option value="building">构建中</Option>
          </Select>
        </Space>

        <Table
          columns={columns}
          dataSource={filteredSites}
          rowKey="id"
          pagination={{
            total: filteredSites.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 新建/编辑站点模态框 */}
      <Modal
        title={editingSite ? '编辑站点' : '新建站点'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingSite(null);
          form.resetFields();
        }}
        onOk={handleSubmit}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: 'stopped',
            ssl: false,
            framework: 'React'
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="站点名称"
                rules={[{ required: true, message: '请输入站点名称' }]}
              >
                <Input placeholder="例如：企业官网" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="domain"
                label="域名"
                rules={[
                  { required: true, message: '请输入域名' },
                  { pattern: /^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$/, message: '请输入有效的域名' }
                ]}
              >
                <Input placeholder="example.com" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="framework"
                label="框架"
                rules={[{ required: true, message: '请选择框架' }]}
              >
                <Select>
                  <Option value="React">React</Option>
                  <Option value="Vue">Vue</Option>
                  <Option value="Next.js">Next.js</Option>
                  <Option value="Nuxt.js">Nuxt.js</Option>
                  <Option value="Static">静态网站</Option>
                  <Option value="WordPress">WordPress</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
              >
                <Select>
                  <Option value="running">运行中</Option>
                  <Option value="stopped">已停止</Option>
                  <Option value="building">构建中</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default SiteList; 